package com.vadmin.vadminjava.servlet;

import com.alibaba.fastjson.JSONObject;
import com.vadmin.vadminjava.aes.AesException;
import com.vadmin.vadminjava.service.WxCouponBusinessService;
import com.vadmin.vadminjava.service.WxCouponCashService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/* ***********************************************************
 *
 * 微信卡券专用通知接口
 *
 * **********************************************************/
@RestController
@RequestMapping ("/WxCouponNotifyServlet")
public class WxCouponNotifyServlet {
    org.slf4j.Logger logger = LoggerFactory.getLogger(WxCouponCashService.class.getName());
    @Autowired
    WxCouponBusinessService wxCouponBusinessService;

    //商家券的通知接收，在内部判断事件类型，当前只有一个领取回调
    @RequestMapping(value={"/couponNotifyDispatchOfBusiness"})
    public String couponNotifyDispatchOfBusiness(@RequestParam Map<String, Object> params,HttpServletRequest req) throws AesException, IOException {
        //参数转jsonobject
        String     ret    = "";
        JSONObject paramJ = new JSONObject();
        params.keySet().forEach(i -> paramJ.put(i, params.get(i)));
        //读取post流
        String         str                 = null;
        StringBuilder  stringBuilder       = new StringBuilder();
        BufferedReader bufferedInputStream = new BufferedReader(new InputStreamReader(req.getInputStream()));
        try {
            while ((str = bufferedInputStream.readLine()) != null) stringBuilder.append(str);
        } finally {
            bufferedInputStream.close();
        }
        String sReqData  = stringBuilder.toString();//这个应该是整个post流，不是表单模式
        logger.info("接收到了商家券回调1>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        ret =  wxCouponBusinessService.couponNotifyDispatchOfBusiness(paramJ,sReqData).toJSONString();
        //TODO 这里的返回可能还要包括http状态码，看文档 ：https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter9_2_15.shtml
        return ret;
    }
}
